package com.lin.csdn.controller;

import com.lin.csdn.service.impl.UserService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/followServlet")
public class FollowServlet extends HttpServlet{

    /**
     *
     * @param req 传入登录用户名字 loginName
     * @param resp
     * @throws ServletException
     * @throws IOException
     *
     * code:0,查找粉丝总数 SeekFanTotal
     * code:1,查找关注总数 SeekFollowTotal
     * code:2,查找粉丝 SeekFan
     * code:3,查找关注 SeekFollow
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding ("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        //建立功能代表的code调用
        String SeekFanTotal="0";
        String SeekFollowTotal="1";
        String SeekFan="2";
        String SeekFollow="3";
        //获取req数据
        String loginName=req.getParameter("loginName");
        String code=req.getParameter("code");

        int result;
        List<Object> name;
        UserService userService=new UserService();
        PrintWriter writer = resp.getWriter(); //响应流
        JSONObject object=new JSONObject();

        //根据需求调用各自的方法
        if(code.equals(SeekFanTotal)) {
            result = userService.beFollow(loginName);
            object.put("beFollow",result);
            writer.print(object);
        }
        else if(code.equals(SeekFollowTotal)){
            result=userService.follow(loginName);
            object.put("follow",result);
            writer.print(object);
        }
        else if(code.equals(SeekFan)){
            JSONArray array=new JSONArray();
            name=userService.beFollowName(loginName);
            for (Object beFollowName : name) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("beFollowName", beFollowName);
                array.put(jsonObject);
            }
            writer.print(array);
        }
        else if(code.equals(SeekFollow)){
            JSONArray array=new JSONArray();
            name=userService.followName(loginName);
            for (Object followName : name) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("followName", followName);
                array.put(jsonObject);
            }
            writer.print(array);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
